<template>
  <view class="page">
    <view class="tabs">
      <view class="tab-item" :class="{ active: activeTab==='snack' }" @click="activeTab='snack'">零食店配置</view>
      <view class="tab-item" :class="{ active: activeTab==='pickup' }" @click="activeTab='pickup'">代取平台配置</view>
      <!-- 暂不开放：退款与风控Tab
      <view class="tab-item" :class="{ active: activeTab==='refund' }" @click="activeTab='refund'">退款与风控</view>
      -->
    </view>

    <view class="section" v-if="activeTab==='snack'">
      <view class="section-title">📦 基础配置</view>
      
      <!-- 配送费 -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">配送费</text>
          <text class="label-desc">每单收取的配送费用</text>
        </view>
        <view class="config-input">
          <text class="input-prefix">¥</text>
          <input 
            class="input-field"
            type="digit"
            v-model="configs.deliveryFee"
            placeholder="请输入配送费"
          />
        </view>
      </view>
      
      <!-- 起送金额 -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">起送金额</text>
          <text class="label-desc">订单最低消费金额</text>
        </view>
        <view class="config-input">
          <text class="input-prefix">¥</text>
          <input 
            class="input-field"
            type="digit"
            v-model="configs.minOrderAmount"
            placeholder="请输入起送金额"
          />
        </view>
      </view>
      
      <!-- 平台名称 -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">平台名称</text>
          <text class="label-desc">小程序展示的名称</text>
        </view>
        <view class="config-input">
          <input 
            class="input-field"
            type="text"
            v-model="configs.platformName"
            placeholder="请输入平台名称"
          />
        </view>
      </view>

      <!-- 首页公告 -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">首页公告</text>
          <text class="label-desc">显示在首页横幅中间的提示文字</text>
        </view>
        <view class="config-input">
          <input 
            class="input-field"
            type="text"
            v-model="configs.homeAnnouncement"
            placeholder="请输入公告，如：星点互助帮为你服务～"
          />
        </view>
      </view>

      <!-- 零食店公告 -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">零食店公告</text>
          <text class="label-desc">显示在零食商城页面顶部的公告信息</text>
        </view>
        <view class="config-input">
          <input 
            class="input-field"
            type="text"
            v-model="configs.snackShopAnnouncement"
            placeholder="如：今日新品上架，欢迎选购～"
          />
        </view>
      </view>

      <!-- 首页轮播图配置 -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">首页轮播图配置</text>
          <text class="label-desc">最多配置3个轮播图，若未配置则使用默认轮播图</text>
        </view>
      </view>

      <!-- 轮播图列表 -->
      <view class="banner-list">
        <view v-for="(banner, index) in bannerConfigs" :key="index" class="banner-card">
          <view class="banner-header">
            <text class="banner-title-text">轮播图 {{ index + 1 }}</text>
            <view class="banner-actions">
              <text class="banner-btn-delete" @click="removeBanner(index)">删除</text>
            </view>
          </view>

          <!-- 标签 -->
          <view class="config-item-inner">
            <text class="label-text-inner">标签</text>
            <input
              class="input-field-inner"
              type="text"
              v-model="banner.badge"
              placeholder="如：服务多样"
            />
          </view>

          <!-- 标题 -->
          <view class="config-item-inner">
            <text class="label-text-inner">标题</text>
            <input
              class="input-field-inner"
              type="text"
              v-model="banner.title"
              placeholder="如：开学啦！"
            />
          </view>

          <!-- 内容/描述 -->
          <view class="config-item-inner">
            <text class="label-text-inner">内容</text>
            <input
              class="input-field-inner"
              type="text"
              v-model="banner.subtitle"
              placeholder="如：下单优惠"
            />
          </view>

          <!-- 背景 -->
          <view class="config-item-inner">
            <view class="label-with-preset">
              <text class="label-text-inner">背景</text>
              <view class="preset-colors">
                <view 
                  v-for="(color, idx) in presetColors" 
                  :key="idx"
                  class="color-dot"
                  :style="{ background: color.value }"
                  @tap="selectBannerColor(index, color.value)"
                />
              </view>
            </view>
            <input
              class="input-field-inner"
              type="text"
              v-model="banner.bgColor"
              placeholder="纯色：#07c160 或 渐变：linear-gradient(135deg,#667eea 0%,#764ba2 100%)"
            />
          </view>

          <!-- 表情 -->
          <view class="config-item-inner">
            <text class="label-text-inner">表情</text>
            <input
              class="input-field-inner"
              type="text"
              v-model="banner.emoji"
              placeholder="如：😎"
            />
          </view>
        </view>
      </view>

      <!-- 添加轮播图按钮 -->
      <view class="config-item" v-if="bannerConfigs.length < 3">
        <view class="btn-add-banner" @click="addBanner">
          <text class="btn-add-text">+ 添加轮播图</text>
        </view>
      </view>

      <!-- 客服联系方式 -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">客服联系方式</text>
          <text class="label-desc">如：微信：xxx，电话：13800000000</text>
        </view>
        <view class="config-input">
          <input 
            class="input-field"
            type="text"
            v-model="configs.customerService"
            placeholder="请输入客服联系方式"
          />
        </view>
      </view>
    </view>
    
    <!-- 代取平台配置 -->
    <view class="section" v-if="activeTab==='pickup'">
      <view class="section-title">🧳 代取平台配置</view>

      <view class="config-item">
        <view class="config-label">
          <text class="label-text">平台服务费率</text>
          <text class="label-desc">百分比（0-100），示例：25.00</text>
        </view>
        <view class="config-input">
          <input class="input-field" type="digit" v-model="configs.pickupPlatformFeeRate" placeholder="请输入费率%" />
          <text class="input-suffix">%</text>
        </view>
      </view>

      <!-- 取快递最低发布价（serviceType=2） -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">取快递最低发布价</text>
          <text class="label-desc">单位：元，低于此价格不允许发布</text>
        </view>
        <view class="config-input">
          <text class="input-prefix">¥</text>
          <input class="input-field" type="digit" v-model="configs.basePriceExpress" placeholder="请输入最低价" />
        </view>
      </view>

      <!-- 取外卖最低发布价（serviceType=3） -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">取外卖最低发布价</text>
          <text class="label-desc">单位：元，低于此价格不允许发布</text>
        </view>
        <view class="config-input">
          <text class="input-prefix">¥</text>
          <input class="input-field" type="digit" v-model="configs.basePriceTakeout" placeholder="请输入最低价" />
        </view>
      </view>

      <!-- 代取奶咖最低发布价（serviceType=4） -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">代取奶咖最低发布价</text>
          <text class="label-desc">单位：元，低于此价格不允许发布</text>
        </view>
        <view class="config-input">
          <text class="input-prefix">¥</text>
          <input class="input-field" type="digit" v-model="configs.basePriceCoffee" placeholder="请输入最低价" />
        </view>
      </view>

      <!-- 其他服务最低发布价（serviceType=5） -->
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">其他服务最低发布价</text>
          <text class="label-desc">单位：元，低于此价格不允许发布</text>
        </view>
        <view class="config-input">
          <text class="input-prefix">¥</text>
          <input class="input-field" type="digit" v-model="configs.basePriceOther" placeholder="请输入最低价" />
        </view>
      </view>
      <!-- 暂不开放：平台微信/支付宝/收款码
      <view class="config-item">
        <view class="config-label">
          <text class="label-text">平台微信</text>
          <text class="label-desc">线下结算微信号/备注</text>
        </view>
        <view class="config-input">
          <input class="input-field" type="text" v-model="configs.pickupPlatformWechat" placeholder="请输入平台微信" />
        </view>
      </view>

      <view class="config-item">
        <view class="config-label">
          <text class="label-text">平台支付宝</text>
          <text class="label-desc">线下结算支付宝账号/备注</text>
        </view>
        <view class="config-input">
          <input class="input-field" type="text" v-model="configs.pickupPlatformAlipay" placeholder="请输入平台支付宝" />
        </view>
      </view>

      <view class="config-item">
        <view class="config-label">
          <text class="label-text">平台收款码URL</text>
          <text class="label-desc">图片URL</text>
        </view>
        <view class="config-input">
          <input class="input-field" type="text" v-model="configs.pickupPlatformQrcode" placeholder="请输入收款码图片URL" />
        </view>
      </view>
      -->
    </view>

    <!-- 暂不开放：退款与风控配置
    <view class="section" v-if="activeTab==='refund'">
      <view class="section-title">♻️ 退款与风控</view>
      ...
    </view>
    -->

    <!-- 保存按钮 -->
    <view class="btn-save" @click="saveConfigs">
      <text class="btn-text">保存配置</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      configs: {
        deliveryFee: '',
        minOrderAmount: '',
        platformName: '',

        pickupPlatformFeeRate: '25.00',
        pickupPlatformWechat: '',
        pickupPlatformAlipay: '',
        pickupPlatformQrcode: '',

        basePriceExpress: '0.00',
        basePriceTakeout: '0.00',
        basePriceCoffee: '0.00',
        basePriceOther: '0.00',

        homeAnnouncement: '',
        snackShopAnnouncement: '',
        homeBannersConfig: '',
        customerService: '',

        refundCompDefault: '0.20',
        refundCompMin: '0.10',
        refundCompMax: '0.50',
        refundMerchantAutoApproveHours: '2',
        refundSnackDeliveringEnabled: true,
        refundAutoApproveEnabled: true
      },
      bannerConfigs: [],
      activeTab: 'snack',
      loading: false,
      existingConfigKeys: [],
      presetColors: [
        { name: '紫蓝渐变', value: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
        { name: '粉红渐变', value: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)' },
        { name: '青绿渐变', value: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)' },
        { name: '蓝天渐变', value: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)' },
        { name: '橙黄渐变', value: 'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)' },
        { name: '绿色', value: '#07c160' },
        { name: '蓝色', value: '#1890ff' },
        { name: '红色', value: '#ff4d4f' },
        { name: '橙色', value: '#ff7a45' },
        { name: '紫色', value: '#722ed1' }
      ]
    }
  },
  onLoad() {
    this.loadConfigs()
  },
  methods: {
    async loadConfigs() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const { getPublicConfigs, getAllConfigs, getPickupBasePrice, getConfig } = require('@/api/config')
        const data = await getPublicConfigs()

        const list = await getAllConfigs()
        const map = {}
        if (Array.isArray(list)) {
          list.forEach(item => {
            if (item && item.configKey) map[item.configKey] = item.configValue || ''
          })
        }
        this.existingConfigKeys = Object.keys(map)

        // 并行获取代取基础价（含其他服务=5）
        let [bp2, bp3, bp4, bp5] = [null, null, null, null]
        try {
          ;[bp2, bp3, bp4, bp5] = await Promise.all([
            getPickupBasePrice(2).catch(() => null),
            getPickupBasePrice(3).catch(() => null),
            getPickupBasePrice(4).catch(() => null),
            getPickupBasePrice(5).catch(() => null)
          ])
        } catch (_) {}

        // 读取公告/客服/首页轮播图配置
        let [ann, snackAnn, cs, bannersConfigStr] = [null, null, null, null]
        try {
          ;[ann, snackAnn, cs, bannersConfigStr] = await Promise.all([
            getConfig('home_announcement').catch(() => ''),
            getConfig('snack_shop_announcement').catch(() => ''),
            getConfig('customer_service').catch(() => ''),
            getConfig('home_banners_config').catch(() => '')
          ])
        } catch (_) {}

        this.configs = {
          deliveryFee: data.deliveryFee || map['delivery_fee'] || '0',
          minOrderAmount: data.minOrderAmount || map['min_order_amount'] || '0',
          platformName: data.platformName || map['platform_name'] || '星点互助帮',

          pickupPlatformFeeRate: map['pickup_platform_fee_rate'] || '25.00',
          pickupPlatformWechat: map['pickup_platform_wechat'] || '',
          pickupPlatformAlipay: map['pickup_platform_alipay'] || '',
          pickupPlatformQrcode: map['pickup_platform_qrcode'] || '',

          basePriceExpress: bp2 != null ? String(bp2) : '0.00',
          basePriceTakeout: bp3 != null ? String(bp3) : '0.00',
          basePriceCoffee: bp4 != null ? String(bp4) : '0.00',
          basePriceOther: bp5 != null ? String(bp5) : '0.00',

          homeAnnouncement: typeof ann === 'string' ? ann : (ann || ''),
          snackShopAnnouncement: typeof snackAnn === 'string' ? snackAnn : (snackAnn || ''),
          homeBannersConfig: typeof bannersConfigStr === 'string' ? bannersConfigStr : (bannersConfigStr || ''),
          customerService: typeof cs === 'string' ? cs : (cs || ''),

          refundCompDefault: map['refund.compensation.rate.default'] || '0.20',
          refundCompMin: map['refund.compensation.rate.min'] || '0.10',
          refundCompMax: map['refund.compensation.rate.max'] || '0.50',
          refundMerchantAutoApproveHours: map['refund.merchant.auto_approve_hours'] || '2',
          refundSnackDeliveringEnabled: (map['refund.snack.delivering.enabled'] || 'true') === 'true' || map['refund.snack.delivering.enabled'] === '1',
          refundAutoApproveEnabled: (map['refund.auto_approve.enabled'] || 'true') === 'true' || map['refund.auto_approve.enabled'] === '1'
        }
        
        // 解析轮播图配置
        try {
          if (this.configs.homeBannersConfig) {
            this.bannerConfigs = JSON.parse(this.configs.homeBannersConfig)
          } else {
            this.bannerConfigs = []
          }
        } catch (e) {
          console.warn('轮播图配置解析失败:', e)
          this.bannerConfigs = []
        }
        
        uni.hideLoading()
      } catch (error) {
        console.error('加载配置失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },
    
    addBanner() {
      if (this.bannerConfigs.length >= 3) {
        uni.showToast({ title: '最多只能配置3个轮播图', icon: 'none' })
        return
      }
      this.bannerConfigs.push({
        badge: '',
        title: '',
        subtitle: '',
        bgColor: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        emoji: '✨'
      })
    },
    
    removeBanner(index) {
      this.bannerConfigs.splice(index, 1)
    },
    
    selectBannerColor(index, colorValue) {
      this.$set(this.bannerConfigs[index], 'bgColor', colorValue)
    },
    
    async saveConfigs() {
      // 校验
      if (!this.validateConfigs()) {
        return
      }
      
      if (this.loading) return
      this.loading = true
      
      try {
        uni.showLoading({ title: '保存中...' })
        
        let configsArray = [
          { configKey: 'delivery_fee', configValue: this.configs.deliveryFee.toString() },
          { configKey: 'min_order_amount', configValue: this.configs.minOrderAmount.toString() },
          { configKey: 'platform_name', configValue: this.configs.platformName },
          { configKey: 'pickup_platform_fee_rate', configValue: this.configs.pickupPlatformFeeRate.toString() }
        ]
        // 首页公告/零食店公告/客服/轮播图配置（若后端已存在对应键则会提交成功）
        configsArray.push(
          { configKey: 'home_announcement', configValue: this.configs.homeAnnouncement || '' },
          { configKey: 'snack_shop_announcement', configValue: this.configs.snackShopAnnouncement || '' },
          { configKey: 'customer_service', configValue: this.configs.customerService || '' },
          { configKey: 'home_banners_config', configValue: JSON.stringify(this.bannerConfigs) }
        )

        // 仅提交后端已存在的配置键，避免后端抛出“配置不存在”
        configsArray = configsArray.filter(item => this.existingConfigKeys.includes(item.configKey))
        
        //console.log('准备发送的配置数据:', JSON.stringify(configsArray))
        
        const { batchUpdateConfigs, updatePickupBasePrice } = require('@/api/config')
        await batchUpdateConfigs(configsArray)
        // 提交基础价（按服务类型）
        await Promise.all([
          updatePickupBasePrice(2, this.configs.basePriceExpress),
          updatePickupBasePrice(3, this.configs.basePriceTakeout),
          updatePickupBasePrice(4, this.configs.basePriceCoffee),
          updatePickupBasePrice(5, this.configs.basePriceOther)
        ])
        
        uni.hideLoading()
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 刷新配置
        setTimeout(() => {
          this.loadConfigs()
        }, 1500)
        
      } catch (error) {
        console.error('保存配置失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    validateConfigs() {
      const c = this.configs
      
      if (!c.deliveryFee || isNaN(c.deliveryFee) || parseFloat(c.deliveryFee) < 0) {
        uni.showToast({
          title: '请输入有效的配送费',
          icon: 'none'
        })
        return false
      }
      
      if (!c.minOrderAmount || isNaN(c.minOrderAmount) || parseFloat(c.minOrderAmount) < 0) {
        uni.showToast({
          title: '请输入有效的起送金额',
          icon: 'none'
        })
        return false
      }
      
      if (!c.platformName || c.platformName.trim() === '') {
        uni.showToast({
          title: '请输入平台名称',
          icon: 'none'
        })
        return false
      }
      if (c.pickupPlatformFeeRate === '' || isNaN(c.pickupPlatformFeeRate)) {
        uni.showToast({ title: '请输入有效的平台费率(0-100)', icon: 'none' })
        return false
      }
      const rate = parseFloat(c.pickupPlatformFeeRate)
      if (rate < 0 || rate > 100) {
        uni.showToast({ title: '平台费率需在0-100之间', icon: 'none' })
        return false
      }
      // 暂不校验退款与风控相关字段

      // 校验基础价
      const priceFields = [
        { key: 'basePriceExpress', label: '取快递最低发布价' },
        { key: 'basePriceTakeout', label: '取外卖最低发布价' },
        { key: 'basePriceCoffee', label: '代取奶咖最低发布价' },
        { key: 'basePriceOther', label: '其他服务最低发布价' }
      ]
      for (const f of priceFields) {
        const v = c[f.key]
        if (v === '' || isNaN(v) || parseFloat(v) < 0) {
          uni.showToast({ title: `请输入有效的${f.label}`, icon: 'none' })
          return false
        }
      }
      
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20rpx;
  padding-bottom: 160rpx;
}

.tabs {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #666;
  border-bottom: 6rpx solid transparent;
}
.tab-item.active {
  color: #333;
  font-weight: 600;
  border-bottom-color: #667eea;
}

.section {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.config-item {
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.config-label {
  margin-bottom: 20rpx;
  
  .label-text {
    display: block;
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .label-desc {
    font-size: 24rpx;
    color: #999;
  }
}

.config-input {
  display: flex;
  align-items: center;
  background: #f5f7fa;
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  
  .input-prefix {
    font-size: 28rpx;
    color: #666;
    margin-right: 8rpx;
  }
  
  .input-field {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  .input-suffix {
    margin-left: 8rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.banner-list {
  padding: 0 32rpx;
  margin-bottom: 20rpx;
}

.banner-card {
  background: #f9f9f9;
  border: 1rpx solid #e8e8e8;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.banner-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  .banner-title-text {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
  }
  
  .banner-actions {
    display: flex;
    gap: 16rpx;
  }
  
  .banner-btn-delete {
    font-size: 24rpx;
    color: #ff4444;
    padding: 8rpx 16rpx;
    background: #fff0f0;
    border-radius: 8rpx;
  }
}

.config-item-inner {
  margin-bottom: 16rpx;
  
  .label-text-inner {
    display: block;
    font-size: 24rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .input-field-inner {
    width: 100%;
    font-size: 26rpx;
    color: #333;
    background: #fff;
    border: 1rpx solid #e0e0e0;
    border-radius: 8rpx;
    padding: 12rpx 16rpx;
    box-sizing: border-box;
    height: 72rpx;
    line-height: 1.5;
  }
  
  .label-with-preset {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
  }
  
  .preset-colors {
    display: flex;
    gap: 8rpx;
    flex-wrap: wrap;
    justify-content: flex-end;
  }
  
  .color-dot {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    border: 2rpx solid #ddd;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
    
    &:active {
      transform: scale(1.1);
      border-color: #333;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
    }
  }
}

.btn-add-banner {
  background: #fff;
  border: 2rpx dashed #667eea;
  border-radius: 12rpx;
  padding: 32rpx;
  text-align: center;
  margin: 20rpx 0;
  
  .btn-add-text {
    font-size: 28rpx;
    color: #667eea;
    font-weight: 600;
  }
}

.btn-save {
  position: fixed;
  bottom: 40rpx;
  left: 32rpx;
  right: 32rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 32rpx;
  border-radius: 40rpx;
  text-align: center;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
  
  .btn-text {
    font-size: 32rpx;
    color: #fff;
    font-weight: bold;
  }
}
</style>

